# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
File    : conftest.py
Time    : 2024/2/20 15:44
author  : mojin
Email   : 397135766@qq.com
-------------------------------------------------------------------------------
"""

import pytest
import time
from common import all_path
from common.logger import Logger

def pytest_terminal_summary(terminalreporter):
    """
    收集测试结果
    """
    _PASSED = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    _ERROR = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    _FAILED = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    _SKIPPED = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    _TOTAL = terminalreporter._numcollected
    _TIMES = time.time() - terminalreporter._sessionstarttime
    Logger.info(f"用例总数: {_TOTAL}")
    Logger.success(f"通过用例: {_PASSED}")
    Logger.error(f"异常用例数: {_ERROR}")
    Logger.error(f"失败用例数: {_FAILED}")
    Logger.warning(f"跳过用例数: {_SKIPPED}")
    Logger.info(f"用例执行时长: {round(_TIMES, 2)} s")
    try:
        _RATE = _PASSED / _TOTAL * 100

        _SUCCESS_RATE=round(_RATE, 2)

    except ZeroDivisionError:
        _SUCCESS_RATE="0.00"
    Logger.info(f"用例成功率:{_SUCCESS_RATE}")
    result_data_test={
        "_TOTAL": f"{_TOTAL}",
        '_PASSED':f"{_PASSED}",
        "_ERROR": f" {_ERROR}",
        "_FAILED": f" {_FAILED}",
        "_SKIPPED": f" {_SKIPPED}",
        "_TIMES": f"{round(_TIMES, 2)} s",
        "_SUCCESS_RATE": f"{_SUCCESS_RATE}",
    }
    #ExchangeData.post_pytest_summary(result_data_test)#测试结果添加到变量池
    with open("result.txt", "w") as fp:#测试结果保存到本地result.txt
        fp.write("_TOTAL=%s" % _TOTAL + "\n")
        fp.write("_PASSED=%s" % _PASSED + "\n")
        fp.write("_FAILED=%s" % _FAILED + "\n")
        fp.write("_ERROR=%s" % _ERROR + "\n")
        fp.write("_SKIPPED=%s" % _SKIPPED + "\n")
        fp.write("_SUCCESS_RATE=%.2f%%" % _SUCCESS_RATE + "\n")
        fp.write("_TIMES=%.2fs" % _TIMES)



@pytest.hookimpl(optionalhook=True)
def pytest_metadata(metadata:dict):
    # 修改或添加环境参数 例如下 可有可无  亦可在 ./config/environment.properties 文件中添加修改
    # 汉字需要转为ASCII编码 在allure中展示才好乱码
    # 手动在线转码 https://www.ip138.com/ascii/，添加到 ./config/environment.properties 文件中
    # 代码 如 ：
    # metadata['ProjectName'] = '建工集团'.encode("unicode_escape").decode()
    pass



def environmental_information(data, parent_key='', sep='_'):
    '''
    获取环境信息
    :param data: 获取到的环境参数字典
    :param parent_key:
    :param sep:
    :return:
    '''
    # environment.properties文本信息为手动添加的环境信息
    # 读取environment.properties文本信息转为字典格式
    with open(all_path.environmentPath, 'r') as file:
        text_data = file.read()
        #print(text_data)
    # 将文本数据分割成行，并以等号为界分割键和值
    key_value_pairs = [line.split('=') for line in text_data.strip().split('\n')]
    # 创建字典并存储键值对
    text_data_to_dict = {key: value for key, value in key_value_pairs}

    #将多层嵌套字典转为，不嵌套的字典格式，一层结构
    flattened_data = {}
    def _flatten(current_data, key):
        for k, v in current_data.items():
            new_key = f"{key}{sep}{k}" if key else k
            if isinstance(v, dict):
                _flatten(v, new_key)
            else:
                flattened_data[new_key] = v
    _flatten(data, parent_key)

    flattened_data.update(text_data_to_dict) #手动添加的环境信息和获取到的环境信息进行合并

    flattened_data = dict(sorted(flattened_data.items())) #字典中按照key名称排序

    # flattened_data 字典格式转为 a=b 字符串格式
    flattened_srt=''
    for k, v in flattened_data.items():
        flattened_srt=flattened_srt+f'{k}={v}\n'

    #写入文本
    with open(all_path.allure_results, 'w', encoding='utf-8') as file:
        file.write(flattened_srt)

@pytest.fixture(scope='session',autouse=True)
def run_environmental_information(metadata): #执行环境版本的获取和添加
    pass

    yield

    #Logger.info(metadata)

    # metadata 获取到的环境参数
    environmental_information(metadata)

